package xml.src.dom4j;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class Dom4JTest2 {
    @Test
    public void parseToList() throws Exception {
        //解析XML文件的数据成为一个List集合
        //导入框架,创建saxReader对象
        SAXReader saxReader = new SAXReader();
        //加载XML文件成为文档对象Document对象
        Document document = saxReader.read(Dom4JTest2.class.getResourceAsStream("/Contacts.xml"));
        //先拿根元素
        Element root = document.getRootElement();
        //提取contact子元素
        List<Element> lists = root.elements("contact");
        //准备一个ArrayList存放联系人信息
        List<Contact> contacts = new ArrayList<>();
        //遍历contacts元素
        for (Element each : lists) {
            Contact contact = new Contact();
            contact.setId(Integer.valueOf(each.attributeValue("id")));
            contact.setVip(Boolean.valueOf(each.attributeValue("vip")));
            contact.setEmail(each.elementTextTrim("email"));
            contact.setGander(each.elementTextTrim("gender").charAt(0));
            contact.setName(each.elementTextTrim("name"));
            //把联系人对象加入到List集合
            contacts.add(contact);
        }
        //遍历List集合
        for (Contact contact : contacts) {
            System.out.println(contact);
        }
    }
}
